<template>
  <div class="page-container">
    <div class="container">
  <el-card shadow="never" style="padding-top: 0">
    <el-tabs v-model="activeTab" type="card" style="padding-top: 0">
      <el-tab-pane label="部门管理" name="departments">
        <el-button type="success" @click="showAddDepartmentDialog = true">新增部门</el-button>
        <el-table :data="departments" style="width: 100%">
          <el-table-column prop="name" label="部门名称"></el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
          <el-table-column prop="managerName" label="部门经理"></el-table-column>
          <el-table-column prop="departmentCount" label="部门人数"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditDepartment(scope.$index, scope.row)">修改</el-button>
              <el-button type="danger" size="small" @click="handleDeleteDepartment(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="职位管理" name="positions">
        <el-button type="success" @click="showAddPositionDialog = true">新增职位</el-button>
        <el-table :data="positions" style="width: 100%">
          <el-table-column prop="name" label="职位名称"></el-table-column>
          <el-table-column prop="departmentName" label="所属部门"></el-table-column>
          <el-table-column prop="positionCount" label="职位人数"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditPosition(scope.$index, scope.row)">修改</el-button>
              <el-button type="danger" size="small" @click="handleDeletePosition(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增部门对话框 -->
    <el-dialog title="新增部门" v-model="showAddDepartmentDialog" width="30%">
      <el-form :model="newDepartment" label-width="80px">
        <el-form-item label="部门名称">
          <el-input v-model="newDepartment.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newDepartment.description"></el-input>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="newDepartment.departmentManagerId" placeholder="请选择部门经理">
            <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.fullName"
                :value="employee.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddDepartmentDialog = false">取消</el-button>
        <el-button type="primary" @click="addDepartment">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑部门对话框 -->
    <el-dialog title="编辑部门" v-model="showEditDepartmentDialog" width="30%">
      <el-form :model="editDepartment" label-width="80px">
        <el-form-item label="部门名称">
          <el-input v-model="editDepartment.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editDepartment.description"></el-input>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="editDepartment.departmentManagerId" placeholder="请选择部门经理">
            <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.fullName"
                :value="employee.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showEditDepartmentDialog = false">取消</el-button>
    <el-button type="primary" @click="editDepartmentSubmit">确定</el-button>
  </span>
    </el-dialog>

    <!-- 新增职位对话框 -->
    <el-dialog title="新增职位" v-model="showAddPositionDialog" width="30%">
      <el-form :model="newPosition" label-width="80px">
        <el-form-item label="职位名称">
          <el-input v-model="newPosition.name"></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="newPosition.departmentId" placeholder="请选择所属部门">
            <el-option
                v-for="department in departments"
                :key="department.id"
                :label="department.name"
                :value="department.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddPositionDialog = false">取消</el-button>
        <el-button type="primary" @click="addPosition">确定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑职位对话框 -->
    <el-dialog title="编辑职位" v-model="showEditPositionDialog" width="30%">
      <el-form :model="editPosition" label-width="80px">
        <el-form-item label="职位名称">
          <el-input v-model="editPosition.name"></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="editPosition.departmentId" placeholder="请选择所属部门">
            <el-option
                v-for="department in departments"
                :key="department.id"
                :label="department.name"
                :value="department.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showEditPositionDialog = false">取消</el-button>
    <el-button type="primary" @click="editPositionSubmit">确定</el-button>
  </span>
    </el-dialog>
  </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import {ElMessage} from "element-plus";

const activeTab = ref('departments');
const showAddDepartmentDialog = ref(false);
const showAddPositionDialog = ref(false);

const departments = ref([]);
const positions = ref([]);
const employees = ref([]);
const showEditDepartmentDialog = ref(false);
const editDepartment = ref({ name: '',
  description: '',
  departmentManagerId: null,});
const newDepartment = ref({
  name: '',
  description: '',
  departmentManagerId: null,
});

const newPosition = ref({
  name: '',
  departmentId: null,
});

onMounted(() => {
  fetchDepartments();
  fetchPositions();
  fetchEmployees();
});
const showEditPositionDialog = ref(false);
const editPosition = ref({});

const handleEditPosition = (index, row) => {
  editPosition.value = {...row};
  showEditPositionDialog.value = true;
};

const editPositionSubmit = async () => {
  try {
    const response = await axios.put(`http://localhost:8080/positions/${editPosition.value.id}`, editPosition.value);
    showEditPositionDialog.value = false;
    ElMessage.success(response.data.message);
    await fetchPositions(); // 刷新职位列表
  } catch (error) {
    console.error('Failed to update position:', error);
  }
};
const handleEditDepartment = (index, row) => {
  // 将要编辑的部门信息复制到 editDepartment 中
  editDepartment.value = {...row};
  showEditDepartmentDialog.value = true;
};

const editDepartmentSubmit = async () => {
  try {
    const response = await axios.put(`http://localhost:8080/departments/${editDepartment.value.id}`, editDepartment.value);
    showEditDepartmentDialog.value = false;
    ElMessage.success(response.data.message);
    await fetchDepartments(); // 刷新部门列表
  } catch (error) {
    console.error('Failed to update department:', error);
  }
};
async function fetchDepartments() {
  try {
    const response = await axios.get('http://localhost:8080/departments');
    departments.value =response.data;
  } catch (error) {
    console.error('Failed to fetch departments:', error);
  }
}

async function fetchPositions() {
  try {
    const response = await axios.get('http://localhost:8080/positions');
    positions.value = response.data
  } catch (error) {
    console.error('Failed to fetch positions:', error);
  }
}

async function fetchEmployees() {
  try {
    const response = await axios.get('http://localhost:8080/employees');
    employees.value = response.data;
  } catch (error) {
    console.error('Failed to fetch employees:', error);
  }
}

async function addDepartment() {
  try {
    const countResponse =await axios.post('http://localhost:8080/departments', newDepartment.value);
    showAddDepartmentDialog.value = false;
    if(countResponse){ElMessage.success(countResponse.data.message);}
    await fetchDepartments();
  } catch (error) {
    console.error('Failed to add department:', error);
  }
}

async function addPosition() {
  try {
    const countResponse =await axios.post('http://localhost:8080/positions', newPosition.value);
    showAddPositionDialog.value = false;
    if(countResponse){ElMessage.success(countResponse.data.message);}
    await fetchPositions();
  } catch (error) {
    console.error('Failed to add position:', error);
  }
}

async function handleDeleteDepartment(index, row) {
  try {
    const countResponse = await axios.get(`http://localhost:8080/employees/countByDepartment/${row.id}`);
    if (countResponse.data > 0) {
      ElMessage.warning('该部门下有员工，无法删除');
      return;
    }
    const countResponse2 = await axios.delete(`http://localhost:8080/departments/${row.id}`);
    if(countResponse2){ElMessage.success(countResponse2.data.message);}
    departments.value.splice(index, 1);
  } catch (error) {
    console.error('Failed to delete department:', error);
  }
}

async function handleDeletePosition(index, row) {
  try {
    const countResponse = await axios.get(`http://localhost:8080/employees/countByPosition/${row.id}`);
    if (countResponse.data > 0) {
      ElMessage.warning('该职位下有员工，无法删除');
      return;
    }
    const countResponse2 =await axios.delete(`http://localhost:8080/positions/${row.id}`);
    if(countResponse2){ElMessage.success(countResponse2.data.message);}
    positions.value.splice(index, 1);
  } catch (error) {
    console.error('Failed to delete position:', error);
  }
}
</script>

<style scoped>
.el-card {
  margin: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-button {
  margin-bottom: 10px;
}
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>